/**
 * 日期格式化
 */
var DateFormat = function(dtobj, format) {
  var o = {
    "M+": dtobj.getMonth() + 1, //month
    "d+": dtobj.getDate(), //day
    "h+": dtobj.getHours(), //hour
    "m+": dtobj.getMinutes(), //minute
    "s+": dtobj.getSeconds(), //second
    "q+": Math.floor((dtobj.getMonth() + 3) / 3), //quarter
    "S": dtobj.getMilliseconds() //millisecond
  }
  if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
    (dtobj.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(format))
      format = format.replace(RegExp.$1,
        RegExp.$1.length == 1 ? o[k] :
          ("00" + o[k]).substr(("" + o[k]).length));
  return format;
};
var ObjEach = function(obj, fn) {
  var key, that = this;
  if (typeof fn !== 'function') return that;
  obj = obj || [];
  if (obj.constructor === Object) {
    for (key in obj) {
      if (fn.call(obj[key], key, obj[key])) break;
    }
  } else {
    for (key = 0; key < obj.length; key++) {
      if (fn.call(obj[key], key, obj[key])) break;
    }
  }
  return that;
};
var objSort = function(data, key, type) {
  //console.log("********************************************************")
  var arr = [],
    compare = function(obj1, obj2) {
      var value1 = obj1['history'][0][key];
      var value2 = obj2['history'][0][key];
      if (value2 < value1) {
        return -1;
      } else if (value2 > value1) {
        return 1;
      } else {
        return 0;
      }
    };
  // for(var key in data){
  // 	console.log(data[key])
  // 	arr.push(data[key]);
  // }
  ObjEach(data, function(index, item) {
    arr.push(item);
  });
  //console.log(arr);
  arr.sort(compare);
  if (type == "asc") arr.reverse();
  return arr;
};
var faces = function() {
  var alt = ["[微笑]", "[嘻嘻]", "[可爱]", "[坏笑]", "[偷笑]", "[害羞]", "[哈哈]", "[失望]", "[悲伤]", "[撇嘴]", "[委屈]", "[汗]", "[晕]",
      "[鄙视]", "[大哭]", "[抓狂]", "[吃惊]", "[疑问]", "[闭嘴]", "[嘘]", "[哈欠]", "[鼓掌]", "[吐舌]", "[馋嘴]", "[奋斗]", "[拜拜]", "[拥抱]",
      "[怒]", "[抱拳]", "[ok]", "[耶]", "[good]", "[NO]", "[握手]", "[来]", "[花]"
    ],
    arr = {};
  alt.forEach(function(index, item) {
    // #ifdef MP-WEIXIN
    arr[index] = 'http://file.fanyuinc.com/face/' + item + '.gif';
    // #endif
    // #ifdef APP-PLUS || H5
    arr[index] = 'http://file.fanyuinc.com/face/' + item + '.gif';
    // #endif
  });
  return arr;
}();
var transferContent = function(content) {
  content = (content || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
    .replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;') //XSS
    .replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;">$1</a>$2') //转义@
    .replace(/face\[([^\s\[\]]+?)\]/g, function(face) { //转义表情
      var alt = face.replace(/^face/g, '');
      return '<img style="vertical-align:middle;width:15px;" src="' + faces[alt] + '"/>';
    })
    .replace(/img\[([^\s]+?)\]/g, function(img) { //转义图片
      return "[图片]";
    })
    .replace(/file\([\s\S]+?\)\[[\s\S]*?\]/g, function(str) { //转义文件
      var href = (str.match(/file\(([\s\S]+?)\)\[/) || [])[1];
      var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
      if (!href) return str;
      return "[文件] " + text;
    })
    .replace(/audio\[([^\s]+?)\]/g, function(audio) { //转义音频
      return "[语音]";
    })
    .replace(/video\[([^\s]+?)\]/g, function(video) { //转义音频
      return "[视频]";
    })
    .replace(/json\[.*\]/g, function(json) { //转义json
      var str = json.replace(/(^json\[)|(\]$)/g, '');
      str = str.replace(/&amp;/g, '&');
      str = str.replace(/&lt;/g, '<');
      str = str.replace(/&gt;/g, '>');
      str = str.replace(/&quot;/g, '"');
      str = str.replace(/&#039;/g, "'");
      str = str.replace(/&#39;/g, "'");
      var obj = JSON.parse(str);
      return obj.title;
    });
  return content;
};
var transferContent2 = function(content) {
  content = (content || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
    .replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;') //XSS
    .replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;">$1</a>$2') //转义@
    .replace(/face\[([^\s\[\]]+?)\]/g, function(face) { //转义表情
      var alt = face.replace(/^face/g, '');
      return '<img style="vertical-align:middle;width:15px;" src="' + faces[alt] + '"/>';
    })
    .replace(/img\[([^\s]+?)\]/g, function(img) { //转义图片
      return "[图片]";
    })
    .replace(/file\([\s\S]+?\)\[[\s\S]*?\]/g, function(str) { //转义文件
      var href = (str.match(/file\(([\s\S]+?)\)\[/) || [])[1];
      var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
      if (!href) return str;
      return "[文件] " + text;
    })
    .replace(/audio\[([^\s]+?)\]/g, function(audio) { //转义音频
      return "[语音]";
    })
    .replace(/video\[([^\s]+?)\]/g, function(video) { //转义音频
      return "[视频]";
    })
    .replace(/json\[.*\]/g, function(json) { //转义json
      var str = json.replace(/(^json\[)|(\]$)/g, '');
      str = str.replace(/&amp;/g, '&');
      str = str.replace(/&lt;/g, '<');
      str = str.replace(/&gt;/g, '>');
      str = str.replace(/&quot;/g, '"');
      str = str.replace(/&#039;/g, "'");
      str = str.replace(/&#39;/g, "'");
      var obj = JSON.parse(str);
      return obj.title;
    });
  var reg = new RegExp('\n', "g");
  return content.replace(reg, '<br/>');
};
var transferContent3 = function(content) {
  content = (content || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
    .replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;') //XSS
    .replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;">$1</a>$2') //转义@
    .replace(/face\[([^\s\[\]]+?)\]/g, function(face) { //转义表情
      var alt = face.replace(/^face/g, '');
      return '<img style="vertical-align:middle;width:15px;" src="' + faces[alt] + '"/>';
    })
    .replace(/img\[([^\s]+?)\]/g, function(img) { //转义图片
      return '<img style="width:100%;" data-src="' + img.replace(/(^img\[)|(\]$)/g, '') + '" src="' + img.replace(
        /(^img\[)|(\]$)/g, '') + '">';
    })
    .replace(/file\([\s\S]+?\)\[[\s\S]*?\]/g, function(str) { //转义文件
      var href = (str.match(/file\(([\s\S]+?)\)\[/) || [])[1];
      var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
      if (!href) return str;
      return "[文件] " + text;
    })
    .replace(/audio\[([^\s]+?)\]/g, function(audio) { //转义音频
      return "[语音]";
    })
    .replace(/video\[([^\s]+?)\]/g, function(video) { //转义音频
      return "[视频]";
    })
    .replace(/json\[.*\]/g, function(json) { //转义json
      var str = json.replace(/(^json\[)|(\]$)/g, '');
      str = str.replace(/&amp;/g, '&');
      str = str.replace(/&lt;/g, '<');
      str = str.replace(/&gt;/g, '>');
      str = str.replace(/&quot;/g, '"');
      str = str.replace(/&#039;/g, "'");
      str = str.replace(/&#39;/g, "'");
      var obj = JSON.parse(str);
      return obj.title;
    });
  var reg = new RegExp('\n', "g");
  return content.replace(reg, '<br/>');
};
var transferDate = function(timestamp) {
  var n = new Date();
  var d = new Date(timestamp || new Date());
  if (n.getDate() == d.getDate() && n.getMonth() == d.getMonth() && n.getFullYear() == d.getFullYear()) {
    return digit(d.getHours()) + ':' + digit(d.getMinutes());
  } else if (n.getDate() == (d.getDate() + 1) && n.getMonth() == d.getMonth() && n.getFullYear() == d.getFullYear()) {
    return "昨天";
  } else {
    return digit(d.getFullYear()) + '/' + digit(d.getMonth() + 1) + '/' + digit(d.getDate());
  }
};
var transferDate2 = function(timestamp) {
  var n = new Date();
  var d = new Date(timestamp || new Date());
  if (n.getDate() == d.getDate() && n.getMonth() == d.getMonth() && n.getFullYear() == d.getFullYear()) {
    return digit(d.getHours()) + ':' + digit(d.getMinutes());
  } else if (n.getDate() == (d.getDate() + 1) && n.getMonth() == d.getMonth() && n.getFullYear() == d.getFullYear()) {
    return '昨天 ' + digit(d.getHours()) + ':' + digit(d.getMinutes());
  } else {
    return digit(d.getFullYear()) + '-' + digit(d.getMonth() + 1) + '-' + digit(d.getDate()) + ' ' + digit(d.getHours()) +
      ':' + digit(d.getMinutes());
  }
};
var digit = function(num, length, end) {
  var str = '';
  num = String(num);
  length = length || 2;
  for (var i = num.length; i < length; i++) {
    str += '0';
  }
  return num < Math.pow(10, length) ? str + (num | 0) : num;
};
var deepCopy = function(obj) {
  var _obj = JSON.stringify(obj),
    objClone = JSON.parse(_obj);
  return objClone;
};
//四舍五入保留2位小数（若第二位小数为0，则保留一位小数
var keepTwoDecimal = function(num) {
  var result = parseFloat(num);
  if (isNaN(result)) {
    console.log("参数错误");
    return false;
  }
  result = Math.round(num * 100) / 100;
  var s_x = result.toString();
  var pos_decimal = s_x.indexOf('.');
  if (pos_decimal < 0) {
    pos_decimal = s_x.length;
    s_x += '.';
  }
  while (s_x.length <= pos_decimal + 1) {
    s_x += '0';
  }
  return s_x;
};
//四舍五入保留2位小数（不够位数，则用0替补）
var keepTwoDecimalFull = function(num) {
  var result = parseFloat(num);
  if (isNaN(result)) {
    console.log("参数错误");
    return false;
  }
  result = Math.round(num * 100) / 100;
  var s_x = result.toString();
  var pos_decimal = s_x.indexOf('.');
  if (pos_decimal < 0) {
    pos_decimal = s_x.length;
    s_x += '.';
  }
  while (s_x.length <= pos_decimal + 2) {
    s_x += '0';
  }
  return s_x;
};
var addressTransition = function(addressObj) {
  var data = {};
  if (addressObj) {
    for (var property in addressObj) {
      data['address[' + property + ']'] = addressObj[property];
    }
  }
  return data;
};
var getSuffix = function(filename) {
  var pos = filename.lastIndexOf('.');
  var suffix = '';
  if (pos != -1) {
    suffix = filename.substring(pos);
  }
  return suffix;
};
//将base64转换为Blob
var dataURLtoBlob=function(dataurl){
  var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
};
module.exports = {
  DateFormat: DateFormat,
  objSort: objSort,
  deepCopy: deepCopy,
  transferContent: transferContent,
  transferContent2: transferContent2,
  transferContent3: transferContent3,
  transferDate: transferDate,
  transferDate2: transferDate2,
  faces: faces,
  keepTwoDecimal: keepTwoDecimal,
  keepTwoDecimalFull: keepTwoDecimalFull,
  addressTransition: addressTransition,
  getSuffix: getSuffix,
  dataURLtoBlob: dataURLtoBlob
}
